package com.mofofa.maozy.components.input

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseEditAction
import com.mofofa.maozy.base.BaseFormAction
import com.mofofa.maozy.databinding.ViewMaozyLoginMobileInputBinding
import com.mofofa.maozy.enums.CountryEnum
import com.mofofa.maozy.extend.*

/**
<declare-styleable name="MaozyLoginAccountInput">
<attr name="cwlmiTitle" format="string" />
<attr name="cwlmiTextColor" format="color" />
<attr name="cwlmiHint" format="string" />
<attr name="cwlmiDelImageRes" format="reference" />
<attr name="cwlmiDelImageHidden" format="boolean" />
<attr name="cwlmiPreHintHidden" format="boolean" />
</declare-styleable>
 * */
class LoginMobileInput : RelativeLayout, BaseFormAction,
    BaseEditAction {

    lateinit var mMaozyViewMaozyBinding: ViewMaozyLoginMobileInputBinding
    private lateinit var vMaozyRootMaozyView: View

    private var cwlmiTextColor: Int = 0
    private var cwlmiHintColor: Int = 0
    private var cwlmiTitle: String? = null
    private var cwlmiText: String? = null
    private var cwlmiHint: String? = null
    private var cwlmiDelImageRes: Int = 0
    private var cwlmiDelImageHidden: Boolean = false
    private var cwlmiPreHintHidden: Boolean = false
    private var cwlmiPreHintLineHidden: Boolean = false
    private var cwlmiPreHintText: String? = null
    private var cwlmiIsTitleBold: Boolean = true
    private var cwlmiTitleSize: Float = 0F

    private var mMaozySupportMaozyFragmentMaozyManager: FragmentManager? = null

    private var mMaozyTempMaozyInputMaozyValue: String = ""
    private var mMaozyOnMaozyActionMaozyClickMaozyListener: (Int) -> Unit = {}
    private var mMaozyOnMaozyTextMaozyChangedMaozyListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(attrs, R.styleable.LoginMobileInput)
                cwlmiTextColor = array.getColor(
                    R.styleable.LoginMobileInput_cwlmiTextColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwlmiText =
                    array.getString(R.styleable.LoginMobileInput_cwlmiText)

                cwlmiTitle =
                    array.getString(R.styleable.LoginMobileInput_cwlmiTitle)

                cwlmiHintColor = array.getColor(
                    R.styleable.LoginMobileInput_cwlmiHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                cwlmiHint =
                    array.getString(R.styleable.LoginMobileInput_cwlmiHint)

                cwlmiDelImageRes =
                    array.getResourceId(
                        R.styleable.LoginMobileInput_cwlmiDelImageRes,
                        R.drawable.maozy_close
                    )
                cwlmiDelImageHidden = array.getBoolean(
                    R.styleable.LoginMobileInput_cwlmiDelImageHidden,
                    false
                )

                cwlmiPreHintHidden = array.getBoolean(
                    R.styleable.LoginMobileInput_cwlmiPreHintHidden,
                    false
                )

                cwlmiPreHintLineHidden = array.getBoolean(
                    R.styleable.LoginMobileInput_cwlmiPreHintLineHidden,
                    false
                )

                cwlmiPreHintText =
                    array.getString(R.styleable.LoginMobileInput_cwlmiPreHintText)

                cwlmiIsTitleBold = array.getBoolean(
                    R.styleable.LoginMobileInput_cwlmiIsTitleBold,
                    false
                )

                cwlmiTitleSize = array.getDimension(
                    R.styleable.LoginMobileInput_cwlmiTitleSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_14
                    ).toFloat()
                )

                array.recycle()
            }
        }
        context?.let {
            vMaozyRootMaozyView =
                View.inflate(it, R.layout.view_maozy_login_mobile_input, this)
            mMaozyViewMaozyBinding =
                ViewMaozyLoginMobileInputBinding.bind(vMaozyRootMaozyView)
            initMaozySubviews()
        }
    }

    override fun initMaozySubviews() {
        try {
            mMaozyViewMaozyBinding.textLoinAccountTitle.text = cwlmiTitle
            mMaozyViewMaozyBinding.textLoinAccountTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwlmiTitleSize
            )
            if (cwlmiIsTitleBold) {
                mMaozyViewMaozyBinding.textLoinAccountTitle.addMaozyBoldMaozyStyle()
            } else {
                mMaozyViewMaozyBinding.textLoinAccountTitle.addMaozyNormalMaozyStyle()
            }

            mMaozyViewMaozyBinding.editLoinAccount.setText(cwlmiText)
            mMaozyViewMaozyBinding.editLoinAccount.setTextColor(cwlmiTextColor)

            mMaozyViewMaozyBinding.editLoinAccount.hint = (cwlmiHint)
            mMaozyViewMaozyBinding.editLoinAccount.setHintTextColor(cwlmiHintColor)

            mMaozyViewMaozyBinding.imageLoginAccountDel.setImageResource(cwlmiDelImageRes)

            mMaozyViewMaozyBinding.llLoginAccountDelBg.setOnClickListener {
                mMaozyOnMaozyActionMaozyClickMaozyListener.invoke(0)
            }

            mMaozyViewMaozyBinding.imageLoginAccountDel.setOnClickListener {
                mMaozyOnMaozyActionMaozyClickMaozyListener.invoke(0)
            }

            mMaozyViewMaozyBinding.textLoinAccountPreHint.text = cwlmiPreHintText

            if (cwlmiPreHintHidden) {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.visibility = GONE
            } else {
                mMaozyViewMaozyBinding.textLoinAccountPreHint.visibility = VISIBLE
            }

            if (cwlmiPreHintLineHidden) {
                mMaozyViewMaozyBinding.vLoinAccountPreHintLine.visibility = GONE
            } else {
                mMaozyViewMaozyBinding.vLoinAccountPreHintLine.visibility = VISIBLE
            }

            mMaozyViewMaozyBinding.editLoinAccount.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isMaozyCompleted()
                    val gContent = getMaozyContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(
                                mMaozyTempMaozyInputMaozyValue,
                                false
                            )
                        ) {
                            try {
                                mMaozyTempMaozyInputMaozyValue = gContent
                                recordMaozyInputMaozyEvent(gContent)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else {
                    //判断是否显示删除按键
                    val tempContent = getMaozyContent()
                    if (tempContent.isNotBlank()) {
                        if (cwlmiDelImageHidden) {
                            mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility = GONE
                        } else {
                            mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility =
                                VISIBLE
                        }
                        mMaozyViewMaozyBinding.textLoinAccountPreHint.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.main_black
                            )
                        )
                    } else {
                        mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility = GONE
                        mMaozyViewMaozyBinding.textLoinAccountPreHint.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.black_7004
                            )
                        )
                    }
                }
            }
            mMaozyViewMaozyBinding.editLoinAccount.addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getMaozyContent()
                    if (tempContent.isNotBlank()) {
                        if (cwlmiDelImageHidden) {
                            mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility = GONE
                        } else {
                            mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility =
                                VISIBLE
                        }
                    } else {
                        mMaozyViewMaozyBinding.llLoginAccountDelBg.visibility = GONE
                    }
                    //回调
                    mMaozyOnMaozyTextMaozyChangedMaozyListener.invoke(
                        tempContent
                    )
                }
            })

            mMaozyViewMaozyBinding.llLoginAccountDelBg.setOnClickListener {
                mMaozyViewMaozyBinding.editLoinAccount.setText("")
            }
            mMaozyViewMaozyBinding.imageLoginAccountDel.setOnClickListener {
                mMaozyViewMaozyBinding.editLoinAccount.setText("")
            }

            //增加星号显示
            mMaozyViewMaozyBinding.textLoinAccountTitle.addMaozyHighlightMaozyStyle(
                mutableListOf("*"),
                ContextCompat.getColor(context, R.color.main_red)
            )

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setMaozyContent(content: String) {
        mMaozyViewMaozyBinding.editLoinAccount.setText(content)
    }

    fun getMaozyContent(): String {
        return mMaozyViewMaozyBinding.editLoinAccount.text.toString().trim()
    }

    fun isMaozyCompleted(): Boolean {
        val gcontent = getMaozyContent()
        if (gcontent.isBlank()) {
            mMaozyViewMaozyBinding.rlLoinAccountBg.setBackgroundResource(R.drawable.maozy_form_input_error)
            mMaozyViewMaozyBinding.llLoginAccountErrTipBg.visibility = VISIBLE
            return false
        }

        mMaozyViewMaozyBinding.llLoginAccountErrTipBg.visibility = GONE
        mMaozyViewMaozyBinding.rlLoinAccountBg.setBackgroundResource(R.drawable.maozy_form_input)
        return true
    }

    fun isMaozyCompletedMaozySlient(): Boolean {
        val gcontent = getMaozyContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }


    override fun toMaozyBeMaozyFocusMaozyPointMaozyAndMaozyShowMaozyInputMaozyKeyboard() {
        try {
            mMaozyViewMaozyBinding.editLoinAccount.isFocusable = true
            mMaozyViewMaozyBinding.editLoinAccount.isFocusableInTouchMode = true
            mMaozyViewMaozyBinding.editLoinAccount.requestFocus()
            Handler(Looper.getMainLooper()).postDelayed({
                context?.let { cxt ->
                    try {
                        val inputMethodManager: InputMethodManager =
                            cxt.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputMethodManager.showSoftInput(
                            mMaozyViewMaozyBinding.editLoinAccount,
                            0
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }, 300)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun toMaozyBeMaozyFocusMaozyPoint() {
        try {
            mMaozyViewMaozyBinding.editLoinAccount.isFocusable = true
            mMaozyViewMaozyBinding.editLoinAccount.isFocusableInTouchMode = true
            mMaozyViewMaozyBinding.editLoinAccount.requestFocus()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setMaozyInputMaozyHint(hint: String) {
        val hintFormat = hint.toMaozyPhoneMaozyNumberMaozyInputMaozyHint()
        mMaozyViewMaozyBinding.editLoinAccount.hint = hintFormat
    }

    fun setMaozyPreMaozyHint(hint: String) {
        mMaozyViewMaozyBinding.textLoinAccountPreHint.text = hint
    }

    override fun setMaozyFragmentMaozyManager(manager: FragmentManager) {
        mMaozySupportMaozyFragmentMaozyManager = manager
    }

    override fun setMaozyOnMaozyActionMaozyClickMaozyListener(listener: (Int) -> Unit) {
        mMaozyOnMaozyActionMaozyClickMaozyListener = listener
    }

    override fun setMaozyOnMaozyTextMaozyChangedMaozyListener(listener: (String) -> Unit) {
        mMaozyOnMaozyTextMaozyChangedMaozyListener = listener
    }

    override fun setMaozyTitle(title: String) {
        cwlmiTitle = title
        mMaozyViewMaozyBinding.textLoinAccountTitle.text = cwlmiTitle
        //增加星号显示
        mMaozyViewMaozyBinding.textLoinAccountTitle.addMaozyHighlightMaozyStyle(
            mutableListOf("*"),
            ContextCompat.getColor(context, R.color.main_red)
        )
    }

    override fun setMaozyDetail(detail: String) {

    }

    override fun setMaozyHint(hint: String) {
        setMaozyInputMaozyHint(hint)
    }

    override fun setMaozyDetailMaozyColor(detailColor: Int) {

    }

    override fun setMaozyTitleMaozyColor(titleColor: Int) {

    }

    fun cleanMaozy() {
        mMaozyViewMaozyBinding.editLoinAccount.setText(null)
    }

    @SuppressLint("SetTextI18n")
    fun updateMaozyLanguage(path: String, customer: String) {
        //hint
        mMaozyViewMaozyBinding.editLoinAccount.hint = customer
        setMaozyTitle(context.getString(R.string.maozy_enter_the_phone_number))

        //区号
        var areaCode = "(+)"
        if (path.contains(CountryEnum.UGANDA.path, true)) {
            areaCode = CountryEnum.UGANDA.areaCode
        }else{
            areaCode = CountryEnum.COTEDIVA.areaCode
        }

//        if (path.contains(CountryEnum.NIGERIA.path, true)) {
//            areaCode = CountryEnum.NIGERIA.areaCode
//
//        } else if (path.contains(CountryEnum.GHANA.path, true)) {
//            areaCode = CountryEnum.GHANA.areaCode
//
//        } else if (path.contains(CountryEnum.UGANDA.path, true)) {
//            areaCode = CountryEnum.UGANDA.areaCode
//
//        } else if (path.contains(CountryEnum.KENYA.path, true)) {
//            setMaozyTitle(context.getString(R.string.maozy_enter_the_phone_number_mpaccount))
//            areaCode = CountryEnum.KENYA.areaCode
//
//        } else if (path.contains(CountryEnum.COTEDIVA.path, true)) {
//            areaCode = CountryEnum.COTEDIVA.areaCode
//
//        } else if (path.contains(CountryEnum.VIETNAM.path, true)) {
//            areaCode = CountryEnum.VIETNAM.areaCode
//        }
        mMaozyViewMaozyBinding.textLoinAccountPreHint.text = areaCode

    }

}